import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kepu/page/animal_detail_page/animal_detail_page.dart';
import 'package:kepu/page/plant_detail_page/plant_detail_page.dart';
import 'package:kepu/page/search_page/provider/search_provider.dart';
import 'package:kepu/widgets/error_widget.dart';
import 'package:kepu/widgets/image_with_title.dart';
import 'package:kepu/widgets/loading_widget.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class SearchPage extends ConsumerStatefulWidget {
  const SearchPage({super.key});

  @override
  ConsumerState<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends ConsumerState<SearchPage> {
  List<String> searchOption = ["搜动物", "搜植物"];
  late TextEditingController _controller;

  @override
  void initState() {
    _controller = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var searchResult = ref.watch(searchProvider);
    var watch = ref.watch(searchOptionProvider);
    return Scaffold(
      appBar: AppBar(title: Text("搜索")),
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Column(
          children: [
            SearchBar(
              controller: _controller,
              shadowColor: WidgetStateProperty.all(
                Theme.of(context).scaffoldBackgroundColor,
              ),
              backgroundColor: WidgetStateProperty.all(
                Theme.of(context).scaffoldBackgroundColor,
              ),
              hintText: "请输入想查询的关键词",
              onSubmitted: (value) {
                // fetch搜索结果
                ref.read(searchProvider.notifier).search(keyword: value);
              },
              onTapOutside: (value) {
                FocusScope.of(context).requestFocus(FocusNode()); //自动关闭键盘
              },

              autoFocus: true,
              trailing: [
                SizedBox(
                  width: 100,
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: TDDropdownMenu(
                      decoration: BoxDecoration(color: Colors.tealAccent.withValues(alpha: 0.4),borderRadius: BorderRadius.circular(20)),
                      direction: TDDropdownMenuDirection.down,
                      items: [
                        TDDropdownItem(
                          options: [
                            TDDropdownItemOption(
                              label: '搜动物',
                              value: '搜动物',
                              selected: watch == "搜动物",
                            ),
                            TDDropdownItemOption(
                              label: '搜植物',
                              value: '搜植物',
                              selected: watch == "搜植物",
                            ),
                          ],
                          onChange: (value) {
                            ref
                                .read(searchOptionProvider.notifier)
                                .switchItem(value[0]);
                          },
                        ),
                      ],
                    ),
                  ),
                ),
                IconButton(
                  onPressed: () {
                    // 等效于提交
                    ref
                        .read(searchProvider.notifier)
                        .search(keyword: _controller.text);
                  },
                  icon: Icon(TDIcons.send, size: 25),
                ),
              ],
            ),
            SizedBox(height: 30),

            searchResult.when(
              data: (data) {
                if (data.isEmpty) {
                  return SizedBox();
                }
                return Expanded(
                  child: EasyRefresh(
                    onLoad:
                        () => ref
                            .read(searchProvider.notifier)
                            .add(keyword: _controller.text),
                    child: ListView.separated(
                      itemBuilder: (context, index) {
                        return InkWell(
                          onTap: () {
                            watch == "搜动物"
                                ? Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder:
                                        (_) => AnimalDetailPage(data[index].id),
                                  ),
                                )
                                : Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder:
                                        (_) => PlantDetailPage(data[index].id),
                                  ),
                                );
                          },
                          child: ImageWithBriefInfo(
                            imageUrl: data[index].image,
                            title: data[index].name,
                            subtitle: data[index].description,
                          ),
                        );
                      },
                      separatorBuilder: (_, _) => Divider(),
                      itemCount: data.length,
                    ),
                  ),
                );
              },
              error: (error, st) => errorWidget(),
              loading: () => loadWidget(context),
            ),
          ],
        ),
      ),
    );
  }
}
